// import 'package:amap_flutter_location/amap_flutter_location.dart';
// import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jyofservice/bean/order_person_entity.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';
import 'package:jyofservice/bean/xiafa_person_entity.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'dart:io';
import 'package:jyofservice/bean/diaodu_detail_entity.dart';
import 'package:sqflite/sqflite.dart';
import 'package:jyofservice/sql/DatabaseHelper.dart';
import 'package:jyofservice/sql/Draft.dart';

//上传附件图片
import 'dart:async';
import 'dart:io';
import 'package:jyofservice/util/Image_picked.dart';
import 'package:path_provider/path_provider.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:jyofservice/util/UploadImageEvent.dart';
import 'package:jyofservice/util/Constants.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'dart:convert' as JSON;

//高德定位

// import 'package:location_permissions/location_permissions.dart';

//客户签名
import 'dart:io';
import 'package:jyofservice/gongdandiaodu/Paint/paint_page.dart';
import 'package:flutter/services.dart';
import 'package:uuid/uuid.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../util/AssetPicker.dart';
import '../util/EncodeUtil.dart';

class DealDiaoDuPage extends StatefulWidget {
  String? view;
  DiaoduDetailDataData? detailStr;
  DraftBean? draftBean;
  bool? ifDraft;

  DealDiaoDuPage({this.view, this.detailStr, this.ifDraft, this.draftBean});

  @override
  _DealDiaoDuPageState createState() => _DealDiaoDuPageState();
}

class _DealDiaoDuPageState extends State<DealDiaoDuPage> {
  TextEditingController _ChuLiTextEditingController =
      new TextEditingController();
  //处理类型
  late OrderPersonEntity typeEntiy;
  List<DropdownMenuItem> typeList = [];
  int? typeId;
  String? typeName;
  //处理人员
  List<DropdownMenuItem> personList = [];
  List personLists = [];
  List clPersonLists = [];
  List clPersonIDLists = [];
  late XiafaPersonEntity personEntity;
  String? personName;
  String? chuLiJieGuo;
  String? chuLiJieGuoType;
  int? personId;
  String personIds = "";
  late SharedPreferences sharedPreferences;
  String? key;
  var zhipaiDate = "";
  String? chuliDate = "";

  //记录从相册选择的附件图片
  List<String> _imageUrls = [];

  //记录工单详情返回图片id
  List<String> _imageIds = [];

  //记录删除工单详情图片id
  List<String> _delFileArr = [];
  String _path = '';

  //记录上传图片ID
  int queueID = 0;

  //eventBus通信
  StreamSubscription? subscriptionType = null;

  //删除未保存的附件
  List _fileArr = [];
  List _pathList = [];

  //定位
  String? _formattedAddress;
  String? _longitude;
  String? _latitude;
  Map<String, Object?>? _locationResult;

  // StreamSubscription<Map<String, Object>>? _locationListener;

  // AMapFlutterLocation _locationPlugin = new AMapFlutterLocation();

  bool isloading = true;

  List<AssetEntity> assets = <AssetEntity>[];

  //url
  var _method = "";
  //工单日志
  var _rizhicontent;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    //获取当前时间
    var dataTime = DateTime.now();

    var XFTime = widget.detailStr!.xFTime;
    print("===$XFTime");
    zhipaiDate = XFTime ?? dataTime.toString().substring(0, 19);
    //如果是维修人员自动显示维修时间
    if (widget.view == "GetMySelfWaitDoWorkConfirm") {
      chuliDate = dataTime.toString().substring(0, 19);
    }
    print("$zhipaiDate==$chuliDate");

    if (widget.ifDraft!) {
      _getPath().then((onValue) {
        if (onValue != null) {
          initData();
        }
      });
      init().then((data) {
        if (data != null) {
          //处理人员单
//        getPersonData();
          //处理人员多选
//          getPersonDataDuoXuan();
//           getfujianarr(widget.detailStr!.lSH);
          //处理类型
          getTypeData();
        }
      });
      subscriptionType =
          Constants.eventBus.on<UploadImageEvent>().listen((event) {
        print("event.resultList==${event.resultList}");
        print("event.pathList==${event.pathList}");

        if (event.resultList!.length > 0) {
          List fileArrs = [];
          for (int i = 0; i < _fileArr.length; i++) {
            String? str = _fileArr[i]["FileName"];
            fileArrs.add(str);
          }

          for (var str in event.resultList!) {
            if (fileArrs.indexOf(str["FileName"]) == -1) {
              _fileArr.add(str);
            }
          }
        }

        if (event.pathList!.length > 0) {
          _pathList.clear();
          for (var str in event.pathList!) {
            _pathList.add(str);
          }
        }

        //取出图片展示
        for (var i = 0; i < _pathList.length; ++i) {
          var path = _pathList[i];

          if (_imageUrls.indexOf(path) == -1) {
            _imageUrls.add(path);
          }
          if (mounted) {
            setState(() {});
          }
        }
      });

      subscriptionType!.resume();
      //getfujianarr(widget.detailStr.lSH);
    } else {
      _getPath();

      init().then((data) {
        if (data != null) {
          //处理人员单
//        getPersonData();
          //处理人员多选
//          getPersonDataDuoXuan();
          getfujianarr(widget.detailStr!.lSH);
          //处理类型
          getTypeData();
        }
      });

      subscriptionType =
          Constants.eventBus.on<UploadImageEvent>().listen((event) {
        print("event.resultList==${event.resultList}");
        print("event.pathList==${event.pathList}");

        if (event.resultList!.length > 0) {
          List fileArrs = [];
          for (int i = 0; i < _fileArr.length; i++) {
            String? str = _fileArr[i]["FileName"];
            fileArrs.add(str);
          }

          for (var str in event.resultList!) {
            if (fileArrs.indexOf(str["FileName"]) == -1) {
              _fileArr.add(str);
            }
          }
        }

        if (event.pathList!.length > 0) {
          _pathList.clear();
          for (var str in event.pathList!) {
            _pathList.add(str);
          }
        }

        //取出图片展示
        for (var i = 0; i < _pathList.length; ++i) {
          var path = _pathList[i];

          if (_imageUrls.indexOf(path) == -1) {
            _imageUrls.add(path);
          }
          if (mounted) {
            setState(() {});
          }
        }
      });

      subscriptionType!.resume();
      //获取定位
      // getAMapLocationData();

      ///注册定位结果监听
      // _locationListener = _locationPlugin
      //     .onLocationChanged()
      //     .listen((Map<String, Object> result) {
      //   setState(() {
      //     _locationResult = result;
      //     print(_locationResult);
      //   });
      // });
    }
  }

  Future initData() async {
    chuliDate = widget.draftBean!.dealTime;
    chuLiJieGuo = widget.draftBean!.dealResult;
    if (chuLiJieGuo == "处理完成") {
      chuLiJieGuoType = "1";
    } else if (chuLiJieGuo == "缓办工单") {
      chuLiJieGuoType = "2";
    }
    _ChuLiTextEditingController.text = widget.draftBean!.dealContent!;
    if (widget.draftBean!.imgeUrls!.length > 0) {
      List<String> list = widget.draftBean!.imgeUrls!.split(",");
      _imageUrls.addAll(list);
    }
    if (widget.draftBean!.imgeIds!.length > 0) {
      _imageIds = widget.draftBean!.imgeIds!.split(",");
      print("_imageIds===$_imageIds");
    }
//    _imageIds.addAll(idlist);

    //判断是否为null或空 否则在未定位到位置情况下保存草稿箱,下次进入此页面会报错
    if (widget.draftBean!.location != "null" &&
        widget.draftBean!.location != "" &&
        widget.draftBean!.location != "定位失败,点击重新获取") {
      _locationResult = {
        "address": widget.draftBean!.location,
        "latitude": double.parse(widget.draftBean!.latitude!),
        "longitude": double.parse(widget.draftBean!.longitude!),
      };
    } else {
      print("====重新获取定位====");
      //重新获取定位
      // getAMapLocationData();
    }
    //获取附件
    imageFile = JSON.jsonDecode(widget.draftBean!.fileArr!);

    if(widget.draftBean!.doType != null){
      typeId = int.parse(widget.draftBean!.doType!);
    }
    typeName = widget.draftBean!.doTypeName;
    print("======$typeName");
    //获取选择的附件
    List assetsList = JSON.jsonDecode(widget.draftBean!.assetsArr!);
    assetsList.forEach((element) {
      assets.add(AssetEntity(
          id: element['id'],
          typeInt: element['type'],
          height: 100,
          width: 100));
    });

    if (widget.draftBean!.delFileArr!.length > 0) {
      _delFileArr = widget.draftBean!.delFileArr!.split(",");
    }
    print("hah:" + _imageUrls.join(","));
    if (mounted) {
      setState(() {});
    }
  }

  /*
  //获取定位
  getAMapLocationData() {
    if (Platform.isAndroid) {
      //android动态请求定位权限
      requestPermission();
    } else {
      ///iOS 获取native精度类型
      requestAccuracyAuthorization();

      //请求定位
      requestLocation();
    }
  }

  ///获取iOS native的accuracyAuthorization类型
  void requestAccuracyAuthorization() async {
    AMapAccuracyAuthorization currentAccuracyAuthorization =
        await _locationPlugin.getSystemAccuracyAuthorization();
    if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
      print("精确定位类型");
    } else if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
      print("模糊定位类型");
    } else {
      print("未知定位类型");
    }
  }

  Future requestLocation() async {
    ///开始定位之前设置定位参数
    _setLocationOption();
    _locationPlugin.startLocation();
  }

  ///设置定位参数
  void _setLocationOption() {
    AMapLocationOption locationOption = new AMapLocationOption();

    ///是否单次定位
    locationOption.onceLocation = true;

    ///是否需要返回逆地理信息
    locationOption.needAddress = true;

    ///逆地理信息的语言类型
    locationOption.geoLanguage = GeoLanguage.DEFAULT;

    locationOption.desiredLocationAccuracyAuthorizationMode =
        AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;

    locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

    ///设置Android端连续定位的定位间隔
    locationOption.locationInterval = 2000;

    ///设置Android端的定位模式<br>
    ///可选值：<br>
    ///<li>[AMapLocationMode.Battery_Saving]</li>
    ///<li>[AMapLocationMode.Device_Sensors]</li>
    ///<li>[AMapLocationMode.Hight_Accuracy]</li>
    locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

    ///设置iOS端的定位最小更新距离<br>
    locationOption.distanceFilter = -1;

    ///设置iOS端期望的定位精度
    /// 可选值：<br>
    /// <li>[DesiredAccuracy.Best] 最高精度</li>
    /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
    /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
    /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
    /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
    locationOption.desiredAccuracy = DesiredAccuracy.Best;

    ///设置iOS端是否允许系统暂停定位
    locationOption.pausesLocationUpdatesAutomatically = false;

    ///将定位参数设置给定位插件
    _locationPlugin.setLocationOption(locationOption);
  }

  Future requestPermission() async {
    PermissionStatus permission =
        await LocationPermissions().checkPermissionStatus();

    if (permission == PermissionStatus.granted) {
      requestLocation();
    } else {
      await LocationPermissions()
          .requestPermissions()
          .then((PermissionStatus permission) {
        if (permission != PermissionStatus.granted) {
          Fluttertoast.showToast(
            msg: "定位请求失败",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 2,
          );

          return;
        } else {
          requestLocation();
        }
      });
    }
  }
  */

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();

    subscriptionType!.cancel();

    ///移除定位监听
    // if (null != _locationListener) {
    //   _locationListener?.cancel();
    // }

    ///销毁定位
    // _locationPlugin.destroy();
  }

  //查看时获取工单附件
  Future getfujianarr(LSH) async {
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "LSH": LSH,
      "ClientType": "phone",
      "ClientKey": aesData
    };

    Response response = await Dio()
        .post(WebConfig().baseUrl + "Work/GetWorkFuJian", data: data);

    print("${WebConfig().baseUrl + "Work/GetWorkFuJian"}=$data");
    print("response:${response.data}");
    if (response.data["Code"] == "200") {
//      "uploadfile/"+ ogj[i].SaveName
      String url = WebConfig().webapiurl + "uploadfile/";

      for (int i = 0; i < response.data["Data"].length; i++) {
        String saveName = response.data["Data"][i]["SaveName"];

        String imageUrl = url + saveName;

        print("imageUrl===$imageUrl");

        _imageUrls.add(imageUrl);
        String id = response.data["Data"][i]["id"].toString();
        _imageIds.add(id);

        if (mounted) {
          setState(() {});
        }
      }
    }

    return response.data;
  }

  //获得应用文档目录
  Future _getPath() async {
    final Directory _directory = await getApplicationDocumentsDirectory();
    final Directory _imageDirectory =
        await new Directory('${_directory.path}/image/')
            .create(recursive: true);
    _path = _imageDirectory.path;
    print('本次获得路径：${_imageDirectory.path}');
    return _path;
  }

  Future logout() async {
    final option = await showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: Text('草稿箱'),
            content: Text('将处理信息保存至草稿箱，下次点开直接发送即可？'),
            actions: <Widget>[
              TextButton(
                child: Text('确定'),
                onPressed: () {
                  //将数据存入数据库中
                  _saveToDraft().then((onValue) {
                    if (onValue > 0) {
                      Fluttertoast.showToast(msg: "已加入草稿箱");
                      Navigator.of(context).pop(false);
                      Navigator.pop(context, false);
                    }
                  });
                },
              ),
              TextButton(
                child: Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop(false);
                },
              )
            ],
          );
        });
  }

  //保存至草稿箱
  Future _saveToDraft() async {
    var db = DatabaseHelper();
    var oldDealBean = await db.getVideo(widget.detailStr!.lSH);
    var result;
    if (oldDealBean != null) {
      //修改
      oldDealBean.lsh = widget.detailStr!.lSH;
      oldDealBean.dealTime = chuliDate;
      oldDealBean.dealResult = chuLiJieGuo;
      oldDealBean.dealResultType = chuLiJieGuoType;
      oldDealBean.dealContent = _ChuLiTextEditingController.text;
      oldDealBean.location = _locationResult != null ? _locationResult!['address'].toString() : '';
      oldDealBean.longitude = _locationResult != null ? _locationResult!['longitude'].toString() : '';
      oldDealBean.latitude = _locationResult != null ? _locationResult!['latitude'].toString() : '';
      oldDealBean.imgeUrls = _imageUrls.join(",");
      oldDealBean.imgeIds = _imageIds.join(",");
      oldDealBean.fileArr = JSON.jsonEncode(imageFile);
      oldDealBean.delFileArr = _delFileArr.join(",");
      oldDealBean.doType = typeId.toString();
      oldDealBean.doTypeName = typeName;
      List list = [];
      assets.forEach((element) {
        var type;
        if (element.type == AssetType.image) {
          type = 1;
        }
        if (element.type == AssetType.video) {
          type = 2;
        }
        if (element.type == AssetType.audio) {
          type = 3;
        }
        if (element.type == AssetType.other) {
          type = 4;
        }

        list.add({'id': element.id, 'type': type});
      });

      oldDealBean.assetsArr = JSON.jsonEncode(list);
      result = await db.updateNote(oldDealBean);
    } else {
      List list = [];
      assets.forEach((element) {
        var type;
        if (element.type == AssetType.image) {
          type = 1;
        }
        if (element.type == AssetType.video) {
          type = 2;
        }
        if (element.type == AssetType.audio) {
          type = 3;
        }
        if (element.type == AssetType.other) {
          type = 4;
        }
        list.add({'id': element.id, 'type': type});
      });
      DraftBean draftBean = DraftBean(
          lsh: widget.detailStr!.lSH,
          dealTime: chuliDate,
          dealResult: chuLiJieGuo,
          dealResultType: chuLiJieGuoType,
          dealContent: _ChuLiTextEditingController.text,
          location: _locationResult != null ? _locationResult!['address'].toString() : '',
          longitude: _locationResult != null ? _locationResult!['longitude'].toString() : '',
          latitude: _locationResult != null ? _locationResult!['latitude'].toString() : '',
          imgeUrls: _imageUrls.join(","),
          imgeIds: _imageIds.join(","),
          fileArr: JSON.jsonEncode(imageFile),
          delFileArr: _delFileArr.join(","),
          doType: typeId.toString(),
          doTypeName: typeName,
          assetsArr: JSON.jsonEncode(list));
      result = await db.insertVideo(draftBean);
    }
    print(result.toString());
    return result;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        Navigator.pop(context, false);
        return Future.value(false);
      },
      child: Scaffold(
          appBar: AppBar(
            centerTitle: true,
            title: Text('工单处理',
                style: TextStyle(
                    color: Colors.white, fontSize: ScreenUtil().setSp(45))),
            leading: IconButton(
                icon: Icon(Icons.arrow_back_ios),
                onPressed: () {
                  Navigator.pop(context, false);
                }),
            actions: <Widget>[
              Offstage(
                  offstage: widget.view == "GetMySelfWaitDoWorkConfirm"
                      ? false
                      : true,
                  child: TextButton(
                    child: Image.asset(
                      'images/caogaoxiang.png',
                      width: ScreenUtil().setWidth(70),
                    ),
                    onPressed: () {
                      logout();
                    },
                  ) //getChuLiRen(),
                  ),
            ],
          ),
          body: Column(
            children: <Widget>[
              Expanded(
                child: Stack(
                  children: <Widget>[
                    SingleChildScrollView(
                      child: Column(
                        children: <Widget>[
                          Container(
                            color: Colors.blue,
                            width: ScreenUtil().screenWidth,
                            height: ScreenUtil().setHeight(100),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                SizedBox(
                                  width: ScreenUtil().setWidth(30),
                                ),
                                Text(
                                  "" ?? '',
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: ScreenUtil().setSp(40)),
                                ),
                                Expanded(
                                  flex: 1,
                                  child: SizedBox(),
                                ),
                                Icon(
                                  Icons.access_time,
                                  color: Colors.white,
                                ),
                                Text("待处理" ?? '',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: ScreenUtil().setSp(40))),
                                SizedBox(
                                  width: ScreenUtil().setWidth(30),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            height: ScreenUtil().setHeight(70),
                            padding: EdgeInsets.fromLTRB(10.0, 10.0, 0, 0),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: <Widget>[
                                Icon(
                                  Icons.person,
                                  color: Colors.blue,
                                ),
                                Text(
                                  '用户信息',
                                  style: TextStyle(
                                      color: Colors.blue,
                                      fontSize: ScreenUtil().setSp(40)),
                                ),
                              ],
                            ),
                          ),
                          getRow("联系人：", widget.detailStr!.linkMan),
                          getRow("联系电话", widget.detailStr!.linkPhone),
                          getRow("住户地址", widget.detailStr!.allName),
                          SizedBox(
                            child: Container(
                              color: Color(0xfff1f1f1),
                            ),
                            height: ScreenUtil().setHeight(25.0),
                          ),
                          Container(
                            child: Column(
                              children: <Widget>[
                                Offstage(
                                  offstage: widget.view ==
                                          "GetMySelfWaitDoWorkConfirm"
                                      ? true
                                      : false,
                                  child: getZhiPaiTime(),
                                ),
                                Container(
                                  height: 1.0,
                                  margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  color: Color(0xffeeeeee),
                                ),
                                Offstage(
                                  offstage: widget.view ==
                                          "GetMySelfWaitDoWorkConfirm"
                                      ? true
                                      : false,
                                  child: getChuLiRenDuoXuan(), //getChuLiRen(),
                                ),
                                Container(
                                  height: 1.0,
                                  margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  color: Color(0xffeeeeee),
                                ),
                                //处理时间 如果是调度不显示
                                Offstage(
                                  offstage:
                                      widget.view == "GetMyAndChildrenWorkForm"
                                          ? true
                                          : false,
                                  child: getChuLiTime(), //getChuLiRen(),
                                ),
                                Container(
                                  height: 1.0,
                                  margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  color: Color(0xffeeeeee),
                                ),
                                //处理结果 如果是调度不显示
                                Offstage(
                                  offstage:
                                      widget.view == "GetMyAndChildrenWorkForm"
                                          ? true
                                          : false,
                                  child: getChuLiType(), //getChuLiRen(),
                                ),
                                Container(
                                  height: 1.0,
                                  margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  color: Color(0xffeeeeee),
                                ),
                                Offstage(
                                  offstage:
                                      widget.view == "GetMyAndChildrenWorkForm"
                                          ? true
                                          : false,
                                  child: getChuLiJieGuo(), //getChuLiRen(),
                                ),
                                Container(
                                  height: 1.0,
                                  margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  color: Color(0xffeeeeee),
                                ),
                                //处理内容 如果是调度不显示
                                Offstage(
                                  offstage:
                                      widget.view == "GetMyAndChildrenWorkForm"
                                          ? true
                                          : false,
                                  child: getChuLiNeiRong(), //getChuLiRen(),
                                ),
                                Container(
                                  height: 1.0,
                                  margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  color: Color(0xffeeeeee),
                                ),
                                SizedBox(
                                    height: 10.0,
                                    child: Container(
                                      color: Colors.black12,
                                    )),
                                //获取定位
                                // Offstage(
                                //   offstage: widget.view == "GetMySelfWaitDoWorkConfirm"
                                //       ? false
                                //       : true,
                                //   child: getAMapLocation(),
                                // ),

                                //添加图片视图 如果是调度不显示
                                Offstage(
                                  offstage:
                                      widget.view == "GetMyAndChildrenWorkForm"
                                          ? true
                                          : false,
                                  child:  JhAssetPicker(
                                    assetType: AssetTypes.image,
                                    lineCount: 3,
                                    selectedAssets: assets,
                                    callBack:
                                        (assetEntityList, CallBackType type) {
                                      if (type == CallBackType.add) {
                                        Navigator.pop(context);
                                      }
                                      print('assetEntityList-------------');
                                      print(assetEntityList);
                                      print('assetEntityList-------------');

                                      assets = assetEntityList;
                                      if (mounted) {
                                        setState(() {});
                                      }
                                    },
                                  ),
                                ),
                                SizedBox(
                                    height: 10.0,
                                    child: Container(
                                      color: Colors.black12,
                                    )),
                                //添加签名视图
                                Offstage(
                                  offstage: widget.view ==
                                          "GetMySelfWaitDoWorkConfirm"
                                      ? false
                                      : true,
                                  child: yhAutograph(), //用户签名视图
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    Offstage(
                      offstage: isloading,
                      child: SpinKitFadingCircle(
                        color: Colors.blue,
                        size: 50.0,
                      ),
                    )
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.fromLTRB(
                    10, 0, 10, ScreenUtil().bottomBarHeight + 20),
                width: ScreenUtil().screenWidth,
                child: Row(
                  children: <Widget>[
                    Expanded(
                        child: Container(
                            height: ScreenUtil().setHeight(100),
                            color: Colors.green,
                            child: TextButton(
                              child: Text(
                                "提交",
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenUtil().setSp(28)),
                              ),
                              onPressed: () {
                                chuLiGongDan();
                              },
                            )))
                  ],
                ),
              ),
            ],
          )),
    );
  }

  //用户签名视图
  Widget yhAutograph() {
    return //客户确认签字
        Container(
      height: ScreenUtil().setHeight(800),
      padding: EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 20.0),
      child: Column(
        children: <Widget>[
          Container(
            alignment: Alignment.topLeft,
            child: TextButton(
              child: Text("点击请用户签字确认",
                  style: TextStyle(
                      color: Colors.blue, fontSize: ScreenUtil().setSp(28))),
              onPressed: () {
                _incrementCounter();
              },
            ),
          ),
          Expanded(
            child: Container(
                decoration: BoxDecoration(
                  border: Border.all(width: 2.0, color: Colors.blue),
                  borderRadius: new BorderRadius.all(new Radius.circular(20.0)),
                ),
//                  margin: EdgeInsets.fromLTRB(0, 0, 0, 20),
                width: ScreenUtil().screenWidth - 120,
                child: GestureDetector(
                  onTap: () {
                    _incrementCounter();
                  },
                  child: (imageFile == null)
                      ? Container(
                          alignment: Alignment.center,
                          color: Colors.white,
                          child: Text(
                            "点  击\n签  字",
                            style: TextStyle(
                                fontSize: 28.0, color: Colors.black12),
                          ),
                        )
                      : Image.file(File(imageFile!), fit: BoxFit.fill),
                )),
          ),
        ],
      ),
    );
  }

  //客户签名
  String? imageFile;

  void _incrementCounter() {
    //跳转绘图页面
    Navigator.push(context, new MaterialPageRoute(builder: (context) {
      return PaintPage();
    })).then((data) {
      print("data:$data");
      imageFile = data;

      if (mounted) {
        setState(() {});
      }
    });
  }

  //处理工单
  chuLiGongDan() {
    _rizhicontent = "处理工单  ";

    if (widget.view == "GetMyAndChildrenWorkForm") {
      //工单调度

      if (zhipaiDate != "") {
        _rizhicontent += "下发时间:[$zhipaiDate];";
      } else {
        Fluttertoast.showToast(
          msg: "请选择指派时间",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 2,
        );

        return;
      }
      if (clPersonIDLists.length > 0) {
        // personId != null单选

        personIds = clPersonIDLists.join(",");
        _rizhicontent += "处理人员:$clPersonLists;";
      } else {
        Fluttertoast.showToast(
          msg: "请选择处理人员",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 2,
        );

        return;
      }
    }

    if (chuliDate != "") {
      _rizhicontent += "处理时间:[$chuliDate];";
    } else {
      if (widget.view == "GetMySelfWaitDoWorkConfirm") {
        Fluttertoast.showToast(
          msg: "请选择处理时间",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 2,
        );

        return;
      }
    }
    if (chuLiJieGuo != null) {
      _rizhicontent += "处理结果:[$chuLiJieGuo];";
    } else {
      if (widget.view == "GetMySelfWaitDoWorkConfirm") {
        Fluttertoast.showToast(
          msg: "请选择处理结果",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 2,
        );

        return;
      }
    }
    if (typeName != null) {
      _rizhicontent += "处理类型:[$typeName];";
    } else {
      if (widget.view == "GetMySelfWaitDoWorkConfirm") {
        Fluttertoast.showToast(
          msg: "请选择处理类型",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 2,
        );

        return;
      }
    }
    if (_ChuLiTextEditingController.text.length > 0) {
      _rizhicontent += "处理内容:[${_ChuLiTextEditingController.text}];";
    } else {
      if (widget.view == "GetMySelfWaitDoWorkConfirm") {
        Fluttertoast.showToast(
          msg: "请填写处理内容",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 2,
        );

        return;
      }
    }

    if (_locationResult != null) {
      _formattedAddress = _locationResult!["address"].toString();
      _longitude = _locationResult!["longitude"].toString();
      _latitude = _locationResult!["latitude"].toString();

      _rizhicontent += "定位地址:[$_formattedAddress 经度:$_longitude 纬度:$_latitude];";
    } else {
      _rizhicontent += "定位地址:[定位失败];";
    }

    if (_fileArr!.length > 0) {
      _rizhicontent += "上传[" + _fileArr!.length.toString() + "]个附件;";
    }
    if (_delFileArr.length > 0) {
      _rizhicontent += "删除[" + _delFileArr.length.toString() + "]个附件;";
    }

    _method = "";
    if (widget.view == "GetMyAndChildrenWorkForm") {
      //工单调度
      _method = "Work/CLworkFormNew";
    } else if (widget.view == "GetMySelfWaitDoWorkConfirm") {
      //我的工单
      _method = "Work/CLmyworkForm";
    }

    if (assets.length > 0 || imageFile != null) {
      //上传图片视频资源后保存工单
      uploadingAssetsData();
    } else {
      //没有添加图片直接保存工单
      saveGongdanData();
    }
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
  }

  //上传图片 文件流上传
  Future uploadingAssetsData() async {
    //附件
    List fileList = [];

    if (mounted) {
      setState(() {
        isloading = false;
      });
    }

    for (int i = 0; i < assets.length; i++) {
      File? file = await assets[i].file;
      if (file != null) {
        var fileType = file.path.substring(file.path.lastIndexOf('.') + 1);
        if (fileType == 'jpg' || fileType == 'jpeg' || fileType == 'png') {
          //获得一个uuud码用于给图片命名
          final String uuid = Uuid().v1();
          final Directory _temp = await getTemporaryDirectory();
          final String _path = _temp.path;
          final result = await FlutterImageCompress.compressAndGetFile(
            file.absolute.path, '${_path}Image_$uuid.jpg',
            minWidth: 1080, //压缩后的最小宽度
            minHeight: 1920, //压缩后的最小高度
            quality: 20, //压缩质量
            rotate: 0, //旋转角度
          );

          fileList.add(result?.path);
        }
      } else {
        Fluttertoast.showToast(
          msg: '文件不存在',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 2,
        );
      }
    }


    //如果有签名 加入数组中
    if (imageFile != null) {
      fileList.add(imageFile);
    }

    print('fileList=====$fileList');

    List formDataArr = [];
    for (int i = 0; i < fileList.length; i++) {
      var name = fileList[i]
          .substring(fileList[i].lastIndexOf("/") + 1, fileList[i].length)
          .toString()
          .replaceAll(" ", "");

      String imageBase64;
      EncodeUtil.image2Base64(fileList[i]).then((
          data) {
        imageBase64 = data; //data.replaceAll('+', "%2B");
        print("imageBase64===$imageBase64");

        var str = {
          "FileName": "$name",
          "Base64Str": "$imageBase64"
        };
        formDataArr.add(str);

        if (fileList.length == formDataArr.length) {
          uploadImageData(formDataArr);
        }
      });

    }

  }

  Future uploadImageData(List fileList) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    String aesData = await AesUtil.encodeBase64();

    print("formDataArr\n${fileList}");


    try {
      Dio dio = new Dio();
      dio.options.connectTimeout = 30000;
      dio.options.receiveTimeout = 30000;

      var data = {
        "key":key,
        "filedata":fileList,"ClientType":"phone","ClientKey":aesData
      };

      Response response = await dio
          .post(WebConfig().baseUrl + "Public/UploadFile", data: data);

      print("response:${response.data}");

      if (response.data["Code"] == "200") {
        var resultList = response.data["Data"];
        print("result===$resultList");

        if (resultList.length > 0) {

          for (int i = 0; i < resultList.length; i++) {
            var str = resultList[i];
            _fileArr.add(str);
          }
        }

        //上传成功提交工单
        saveGongdanData();
      } else {
        if (mounted) {
          setState(() {
            isloading = true;
          });
        }

        Fluttertoast.showToast(
          msg: response.data["Data"]["Msg"].toString(),
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 2,
        );
      }

      return response.data;
    } catch (e) {
      if (mounted) {
        setState(() {
          isloading = true;
        });
      }

      Fluttertoast.showToast(
        msg: e.toString(),
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 2,
      );
    }
  }

  Future saveGongdanData() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "LSH": widget.detailStr!.lSH,
      "XFTime": zhipaiDate,
      "CLUserId": personIds ?? "",
      "CLTime": chuliDate,
      "Result": chuLiJieGuoType ?? "",
      "Remarks": _ChuLiTextEditingController.text,
      "rizhicontent": _rizhicontent,
      //处理类型
      "doType": typeId,
      "lat": _latitude,
      "lng": _longitude,
      "Adress": _formattedAddress,
      "fujian": _fileArr,
      "delfilearr":  _delFileArr.join(','),
      "ClientType": "phone",
      "ClientKey": aesData
    };

    Response response =
        await Dio().post(WebConfig().baseUrl + _method, data: data);

    print("${WebConfig().baseUrl + _method}=$data");
    print("response:${response.data}");
    if (response.data["Code"] == "200") {
      isloading = true;

      Fluttertoast.showToast(
        msg: "操作成功",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 2,
      );
      var reslut = await DatabaseHelper().deleteNote(widget.detailStr!.lSH);
      Navigator.pop(context, true);
    } else {
      Fluttertoast.showToast(
        msg: response.data["Msg"].toString(),
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 2,
      );
      isloading = true;
    }

    return response.data;
  }

  //指派时间
  Widget getZhiPaiTime() {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '指派时间',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: Container(
              padding: EdgeInsets.all(2),
//              height: ScreenUtil().setHeight(80),
              child: Row(
                children: <Widget>[
                  TextButton(
                      onPressed: () {
                        DatePicker.showDateTimePicker(context,
                            showTitleActions: true, onChanged: (date) {
                          print('change $date');
                        }, onConfirm: (date) {
                          print('confirm $date');
                          if (mounted) {
                            setState(() {
                              zhipaiDate = date.toString().substring(0, 19);
                            });
                          }
                        }, currentTime: DateTime.now(), locale: LocaleType.zh);
                      },
                      child: Container(
                        padding: EdgeInsets.fromLTRB(0, 10, 10, 10),
                        child: Text(
                          zhipaiDate.length > 0 ? zhipaiDate : '请选择',
                          style: TextStyle(
                              color: Color(0xFFB6B6B6),
                              fontSize: ScreenUtil().setSp(30)),
                        ),
                      )),
                ],
              ),
            ),
          ),
          Icon(
            Icons.keyboard_arrow_right,
            color: Color(0xff666666),
          )
        ],
      ),
    );
  }

  //处理人员单选
  Widget getChuLiRen() {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '处理人员',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(50),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              width: double.infinity,
//              height: ScreenUtil().setHeight(80),
              //1.用DropdownButtonHideUnderline包裹DropdownButton 取消下划线
              child: DropdownButton(
                underline: new Container(),
                //2.取消下划线
                isExpanded: true,
                value: personName,
                items: personList,
                hint: Text('请选择',
                    style: TextStyle(
                        color: Color(0xFFB6B6B6),
                        fontSize: ScreenUtil().setSp(30))),
                onChanged: (dynamic T) {
                  if (mounted) {
                    setState(() {
                      personName = T;

                      for (int i = 0; i < personEntity.data!.length; i++) {
                        if (personEntity.data![i].realName == personName) {
                          personId = personEntity.data![i].iD;
                        }
                      }
                    });
                  }
                },

                icon: Icon(Icons.keyboard_arrow_right),
                style: new TextStyle(
                    //设置文本框里面文字的样式
                    color: Colors.black),
              ),
            ),
          ),
        ],
      ),
    );
  }

  //处理人多选
  Widget getChuLiRenDuoXuan() {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '处理人员',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
                width: double.infinity,
                child: TextButton(
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.fromLTRB(2, 10, 10, 10),
                    child: Text(
                        clPersonLists.length > 0
                            ? "${clPersonLists.toString()}"
                            : "请选择",
                        style: TextStyle(
                            color: Color(0xFFB6B6B6),
                            fontSize: ScreenUtil().setSp(30))),
                  ),
                  onPressed: () {
                    getPersonDataDuoXuan().then((data) {
                      if (data) {
                        showMyDialog();
                      }
                    });
                  },
                )),
          ),
          Icon(
            Icons.keyboard_arrow_right,
            color: Color(0xff666666),
          ),
        ],
      ),
    );
  }

  void showMyDialog() {
    //处理人员弹框
    showDialog(
        context: context,
        builder: (ctx) {
          return StatefulBuilder(
            builder: (context, state) {
              return SimpleDialog(
                title: Text("选择处理人员"),
                titlePadding: EdgeInsets.all(10),
                backgroundColor: Colors.white,
                elevation: 5,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(6))),
                children: <Widget>[
                  Container(
                    width: 200,
                    height: 300,
                    child: ListView.builder(
                      itemCount: personLists.length,
                      itemBuilder: (context, index) {
                        return Column(
                          children: <Widget>[
                            GestureDetector(
                              child: Container(
                                height: 50.0,
                                padding: EdgeInsets.only(left: 20.0),
                                width: 360.0,
                                child: Row(
                                  children: <Widget>[
                                    Image.asset(
                                      personLists[index]["isSelect"]
                                          ? "images/yixuanze.png"
                                          : "images/weixuanze.png",
                                      width: ScreenUtil().setWidth(40),
                                    ),
                                    SizedBox(
                                      width: 10.0,
                                    ),
                                    Expanded(
                                        child: Text(
                                            "${personLists[index]["realName"]}")),
                                  ],
                                ),
                              ),
                              onTap: () {
                                //取出点击的index
                                bool isSelect = personLists[index]["isSelect"];
                                print("$isSelect");
                                if (!isSelect) {
                                  getPersonTongYiBuMen(personLists[index]["ID"])
                                      .then((data) {
                                    print(
                                        "data===$data=${personLists[index]["ID"]}");
                                    if (data) {
                                      personLists[index]["isSelect"] = true;
                                      clPersonLists
                                          .add(personLists[index]["realName"]);
                                      clPersonIDLists
                                          .add(personLists[index]["ID"]);
                                    }

                                    state(() {});
                                  });
                                } else {
                                  personLists[index]["isSelect"] = false;
                                  for (int i = 0;
                                      i < clPersonIDLists.length;
                                      i++) {
                                    if (clPersonIDLists[i] ==
                                        personLists[index]["ID"]) {
                                      clPersonIDLists.removeAt(i);
                                    }
                                  }

                                  for (int i = 0;
                                      i < clPersonLists.length;
                                      i++) {
                                    if (clPersonLists[i] ==
                                        personLists[index]["realName"]) {
                                      clPersonLists.removeAt(i);
                                    }
                                  }
                                }

                                state(() {});
                              },
                            ),
                            Divider(),
                          ],
                        );
                      },
                    ),
                  ),
                  Container(
                      height: 40,
                      child: Row(
                        children: <Widget>[
                          SizedBox(
                            width: 20.0,
                          ),
                          Expanded(
                              child: TextButton(
                            style: ButtonStyle(
                                backgroundColor:
                                    WidgetStateProperty.all(Colors.black12)),
                            child: Text("取消"),
                            onPressed: () {
                              clPersonLists.clear();
                              clPersonIDLists.clear();
                              //处理人员多选
                              getPersonDataDuoXuan();
                              if (mounted) {
                                setState(() {});
                              }
                              Navigator.pop(context);
                            },
                          )),
                          SizedBox(
                            width: 10.0,
                          ),
                          Expanded(
                              child: TextButton(
                            style: ButtonStyle(
                                backgroundColor:
                                    WidgetStateProperty.all(Colors.blue)),
                            child: Text(
                              "确定",
                              style: TextStyle(color: Colors.white),
                            ),
                            onPressed: () {
                              if (mounted) {
                                setState(() {});
                              }

                              Navigator.pop(context);
                            },
                          )),
                          SizedBox(
                            width: 20.0,
                          )
                        ],
                      ))
                ],
              );
            },
          );
        });
  }

  //处理时间
  Widget getChuLiTime() {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '处理时间',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(50),
          ),
          Expanded(
            flex: 1,
            child: Container(
              padding: EdgeInsets.all(2),
//              height: ScreenUtil().setHeight(80),
              child: Row(
                children: <Widget>[
                  GestureDetector(
                    onTap: () {
                      //如果不是维修人员, 调度人员可以选择时间
                      if (widget.view != "GetMySelfWaitDoWorkConfirm") {
                        DatePicker.showDateTimePicker(context,
                            showTitleActions: true, onChanged: (date) {
                          print('change $date');
                        }, onConfirm: (date) {
                          print('confirm $date');
                          if (mounted) {
                            setState(() {
                              chuliDate = date.toString().substring(0, 19);
                            });
                          }
                        }, currentTime: DateTime.now(), locale: LocaleType.zh);
                      }
                    },
                    child: Container(
                      width: ScreenUtil().setHeight(380),
                      padding: EdgeInsets.fromLTRB(0, 10, 10, 10),
                      child: Text(
                        chuliDate!.length > 0 ? chuliDate! : '请选择',
                        style: TextStyle(
                            color: Color(0xFFB6B6B6),
                            fontSize: ScreenUtil().setSp(30)),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
          Offstage(
            //如果是维修人员 隐藏图标
            offstage: widget.view == "GetMySelfWaitDoWorkConfirm",
            child: Icon(
              Icons.keyboard_arrow_right,
              color: Color(0xff666666),
            ),
          )
        ],
      ),
    );
  }

  //定位位置
  // Widget getAMapLocation() {
  //   return Container(
  //     padding: EdgeInsets.all(10),
  //     child: Row(
  //       crossAxisAlignment: CrossAxisAlignment.center,
  //       children: <Widget>[
  //         Icon(Icons.location_on),
  //         Text(
  //           '定位地址',
  //           style: TextStyle(
  //               color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
  //         ),
  //         SizedBox(
  //           width: ScreenUtil().setWidth(10),
  //         ),
  //         Expanded(
  //           flex: 1,
  //           child: Container(
  //             alignment: Alignment.centerLeft,
  //             child: TextButton(
  //               onPressed: () {
  //                 //重新获取定位
  //                 getAMapLocationData();
  //               },
  //               child: Text(
  //                 _locationResult == null
  //                     ? "正在获取定位..."
  //                     : (_locationResult!['address'] == null
  //                         ? "定位失败,点击重新获取"
  //                         : _locationResult!['address'].toString()),
  //                 style: TextStyle(color: Colors.blue),
  //               ),
  //             ),
  //           ),
  //         )
  //       ],
  //     ),
  //   );
  // }

  //处理内容
  Widget getChuLiNeiRong() {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '处理内容',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(50),
          ),
          Expanded(
              flex: 1,
              child: Container(
                height: ScreenUtil().setWidth(160),
                width: ScreenUtil().setWidth(500),
                color: Color(0xfff2f5f9),
                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(width: 1.0, color: Colors.black12),
                    borderRadius: BorderRadius.circular(2.5),
//                                               color: Colors.white,
                  ),
                  child: TextField(
                    textAlign: TextAlign.start,
                    maxLines: null,
                    onSubmitted: (text) {
                      //内容提交(按回车)的回调

                      print('submit $text');
                    },
                    controller: _ChuLiTextEditingController,
                    textInputAction: TextInputAction.done,
                    decoration: InputDecoration(
//                                                 hintText: "请输入",
//                                                 hintStyle: TextStyle(fontSize: ScreenUtil().setSp(28.0)),
//                                                  enabledBorder: OutlineInputBorder(
//                                                    /*边角*/
//                                                    borderRadius: BorderRadius.all(
//                                                      Radius.circular(5), //边角为30
//                                                    ),
//                                                    borderSide: BorderSide(
//                                                      color: Colors.black12, //边线颜色为黄色
//                                                      width: 1.0, //边线宽度为2
//                                                    ),
//                                                  ),
                      fillColor: Color(0xfff2f5f9),
                      contentPadding: EdgeInsets.all(10.0),
                      border: InputBorder.none,
                    ),
                  ),
                ),
              )),
        ],
      ),
    );
  }

  //处理类型
  Widget getChuLiType() {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '处理类型',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(50),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              width: double.infinity,
//              height: ScreenUtil().setHeight(80),
              //1.用DropdownButtonHideUnderline包裹DropdownButton 取消下划线
              child: DropdownButton(
                underline: new Container(),
                //2.取消下划线
                isExpanded: true,
                value: typeName,
                items: typeList,
                hint: Text('请选择',
                    style: TextStyle(
                        color: Color(0xFFB6B6B6),
                        fontSize: ScreenUtil().setSp(30))),
                onChanged: (dynamic T) {
                  if (mounted) {
                    setState(() {
                      typeName = T;
                      for (int i = 0; i < typeEntiy.data!.length; i++) {
                        if (typeEntiy.data![i].name == typeName) {
                          typeId = typeEntiy.data![i].iD;
                        }
                      }
                    });
                  }

                  print("处理类型==$chuLiJieGuoType");
                },

                icon: Icon(Icons.keyboard_arrow_right),
                style: new TextStyle(
                    //设置文本框里面文字的样式
                    color: Colors.black),
              ),
            ),
          ),
        ],
      ),
    );
  }

  //处理结果
  Widget getChuLiJieGuo() {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '处理结果',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(50),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              width: double.infinity,
//              height: ScreenUtil().setHeight(80),
              //1.用DropdownButtonHideUnderline包裹DropdownButton 取消下划线
              child: DropdownButton(
                underline: new Container(),
                //2.取消下划线
                isExpanded: true,
                value: chuLiJieGuo,
                items: getListData(),
                hint: Text('请选择',
                    style: TextStyle(
                        color: Color(0xFFB6B6B6),
                        fontSize: ScreenUtil().setSp(30))),
                onChanged: (dynamic T) {
                  if (mounted) {
                    setState(() {
                      chuLiJieGuo = T;

                      if (chuLiJieGuo == "处理完成") {
                        chuLiJieGuoType = "1";
                      } else if (chuLiJieGuo == "缓办工单") {
                        chuLiJieGuoType = "2";
                      }
                    });
                  }

                  print("处理结果==$chuLiJieGuoType");
                },

                icon: Icon(Icons.keyboard_arrow_right),
                style: new TextStyle(
                    //设置文本框里面文字的样式
                    color: Colors.black),
              ),
            ),
          ),
        ],
      ),
    );
  }

  List<DropdownMenuItem> getListData() {
    List<DropdownMenuItem> items = [];
    DropdownMenuItem dropdownMenuItem1 = new DropdownMenuItem(
      child: new Text('处理完成'),
      value: '处理完成',
    );
    items.add(dropdownMenuItem1);
//    DropdownMenuItem dropdownMenuItem2 = new DropdownMenuItem(
//      child: new Text('缓办工单'),
//      value: '缓办工单',
//    );
//    items.add(dropdownMenuItem2);

    return items;
  }

  //获取key
  Future init() async {
    sharedPreferences = await SharedPreferences.getInstance();
    key = sharedPreferences.getString("key");
    return key;
  }

  //获取处理类型
  Future getTypeData() async {
    typeList.clear();
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "GD_dotype",
      "wherestr": "1=1",
      "idstr": "ID",
      "namestr": "Name",
      "ClientType": "phone",
      "ClientKey": aesData
    };
    Response response =
        await Dio().post(WebConfig().baseUrl + "DB/getchoosedata", data: data);
    typeEntiy = OrderPersonEntity.fromJson(response.data);
    print("====${response.data.toString()}");

    if (typeEntiy.code == "200") {
      if (mounted) {
        setState(() {
          typeList = new List<DropdownMenuItem>.generate(
              typeEntiy.data!.length,
              (i) => new DropdownMenuItem(
                  child: new Text(
                    typeEntiy.data![i].name ?? "",
                    style: TextStyle(
                        color: Colors.black87,
                        fontSize: ScreenUtil().setSp(35)),
                  ),
                  value: typeEntiy.data![i].name.toString() ?? ""));
        });
      }
    }
    return response.data;
  }

  //获取处理人员单选
  Future getPersonData() async {
    print("widget.departmentId==${widget.detailStr}");
    personList.clear();
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "Department_id": widget.detailStr!.departmentId,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    Response response = await Dio()
        .post(WebConfig().baseUrl + "Work/GetXiaFaRenYuan", data: data);
    personEntity = XiafaPersonEntity.fromJson(response.data);
    print(response.data.toString());

    if (personEntity.code == "200") {
      if (mounted) {
        setState(() {
          personList = new List<DropdownMenuItem>.generate(
              personEntity.data!.length,
              (i) => new DropdownMenuItem(
                  child: new Text(
                    personEntity.data![i].realName ?? "",
                    style: TextStyle(
                        color: Colors.black87,
                        fontSize: ScreenUtil().setSp(35)),
                  ),
                  value: personEntity.data![i].realName.toString() ?? ""));
        });
      }
    }

    return response.data;
  }

  //获取处理人员多选
  Future getPersonDataDuoXuan() async {
    print("widget.departmentId==${widget.detailStr}");
    personLists.clear();
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "Department_id": widget.detailStr!.departmentId,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    Response response = await Dio()
        .post(WebConfig().baseUrl + "Work/GetXiaFaRenYuan", data: data);
    personEntity = XiafaPersonEntity.fromJson(response.data);
    print(response.data.toString());

    if (personEntity.code == "200") {
      for (int i = 0; i < personEntity.data!.length; i++) {
        var json = {
          "ID": personEntity.data![i].iD,
          "realName": personEntity.data![i].realName,
          "isSelect": false
        };

        personLists.add(json);
      }

      print("personLists===$personLists");
      if (mounted) {
        setState(() {});
      }

      return true;
    } else {
      Fluttertoast.showToast(msg: "${personEntity.msg}");
    }

    return response.data;
  }

  //判断选中处理人员是否属于同一部门
  Future getPersonTongYiBuMen(personID) async {
    List ssd = [];
    for (int i = 0; i < clPersonIDLists.length; i++) {
      ssd.add(clPersonIDLists[i]);
    }

    ssd.add(personID);
    var sdg = ssd.join(",");
    String aesData = await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "sdg": sdg,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print("data===$data");
    Response response =
        await Dio().post(WebConfig().baseUrl + "DB/YanZhengBuMen", data: data);
    print(response.data.toString());
    if (response.data["Code"] == "200") {
      if (response.data["Data"] > 1) {
        Fluttertoast.showToast(msg: "请选择同一部门下的维修人员！");
        return false;
      } else {
        return true;
      }
    }
  }

  Widget getRow(String str1, String? str2) {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Text(
            str1 ?? '',
            style: TextStyle(
                color: Color(0xff666666), fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(40),
          ),
          Container(
            color: Colors.grey,
            height: ScreenUtil().setHeight(40),
            width: ScreenUtil().setWidth(2),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(20),
          ),
          Expanded(
            flex: 1,
            child: Text(
              str2 ?? '',
              style: TextStyle(
                  color: Color(0xff666666), fontSize: ScreenUtil().setSp(35)),
            ),
          ),
        ],
      ),
    );
  }
}
